<?php

/***  DOCUMENTATION LAYER

	Greqo Blogger Request Library

	Last Update: Dec 2006
	Author: Tom Atwell (klenwell@gmail.com)

	FUNCTIONS
		greqo_blogger_request_factory($request_url, $request_method, $HEADERS=0, $body_data='')
		greqo_blogger_fetch_feed($num_entries=15, $start=1, $type='full')
		greqo_blogger_get_blog_list()
		greqo_blogger_post_entry($message, $title='')
		greqo_blogger_edit_entry($entry_id, $message, $title='')
		greqo_blogger_delete_entry($entry_id)

  NOTES

______________________________________________________________________________*/


// greqo_blogger_request_factory
/*____________________________________________________________________________*/
function greqo_blogger_request_factory($request_url, $request_method, $HEADERS=0, $body_data='')
{
// *** DATA

	// Global
	global $GREQO;
	
	// Static redirect flag (limit to one redirect attempt)
	static $redirect_ok = 1;
	
	// New/Old Flag (inactive -- how to distinguish?)
	$_FLAG['old_account'] = 0;

	// Return
	$RESPONSE = array
	(
		'code' => 0,
		'code_class' => 0,
		'body' => '',
	);


// *** MANIPULATE

	// Load PEAR Classes
	greqo_load_gdata_classes();
	
	// PEAR Http Config
	$_CONFIG = array( 'timeout' => 10 );	
	
	// Create PEAR Client
	$GDATA_CLIENT = new HTTP_Request($request_url, $_CONFIG);
	
	// Set Method
	$GDATA_CLIENT->setMethod($request_method);
	
	// Old Accounts: basic authorization
	if ( $GREQO['BLOGGER']['is_old_account'] )
	{
		$_LOGIN = greqo_blogger_get_user_data();
		$GDATA_CLIENT->setBasicAuth($_LOGIN['user'], $_LOGIN['password']);
	}
	
	// New Accounts: Google authorization
	// note: once old accounts can use this, remove the else bracket
	else
	{
		// get session token
  	if ( !empty($_SESSION['GDATA']['auth_token']) ) 
  	{
  		$session_token = $_SESSION['GDATA']['auth_token'];
			$GDATA_CLIENT->addHeader('authorization', 'GoogleLogin auth=' . $session_token);
  	}
  	else
  	{
  		trigger_error('no Google session token found - will attempt to request without setting auth token but failure likely', E_USER_WARNING);
  	}	
	}	
	
	// Add additional headers
	if ( is_array($HEADERS) )
	{
		foreach ( $HEADERS as $_key => $_value )
  	{
  		$GDATA_CLIENT->addHeader($_key, $_value);
  	}
	}	
	
	// Add request body
	if ( !empty($body_data) ) $GDATA_CLIENT->addRawPostData($body_data, 1);
	
	// Send Request
	$GResult = $GDATA_CLIENT->sendRequest();
	
	// Check for Errors
	if ( PEAR::isError($GResult) )
	{
		trigger_error('request failed: ' . $GResult->getMessage(), E_USER_WARNING);
		return 0;
	}
	
	// Get Response
	$RESPONSE['code'] = $GDATA_CLIENT->getResponseCode();
	$RESPONSE['code_class'] = floor($RESPONSE['code'] / 100);
	$RESPONSE['body'] = $GDATA_CLIENT->getResponseBody();
	$RESPONSE['HEADER'] = $GDATA_CLIENT->getResponseHeader();
	
	// Redirect: attempt once more
	if ( $RESPONSE['code_class'] == 3 && $redirect_ok )
	{
		$redirect_ok = 0;
		if ( $request_url = $GDATA_CLIENT->getResponseHeader('Location') )
		{
			trigger_error("Redirect Code {$RESPONSE['code']} - Redirecting to: $request_url");
			$RESPONSE = greqo_blogger_request_factory($request_url, $request_method, $HEADERS, $body_data);
		}
		else
		{
			trigger_error("Redirect Code {$RESPONSE['code']}: Request sent to: $request_url / location header for redirect not found", E_USER_WARNING);
		}
	}
	// Redirect: second attempt
	elseif ( $RESPONSE['code_class'] == 3 )
	{
		if ( !$_location = $GDATA_CLIENT->getResponseHeader('Location') ) $_location = 'not found';
		trigger_error("Second Redirect Code {$RESPONSE['code']}: location header='{$_location}' / Request sent to: $request_url", E_USER_WARNING);
	}


// *** RETURN

	return $RESPONSE;

} // end Fx
/*____________________________________________________________________________*/


// greqo_blogger_fetch_feed
/*____________________________________________________________________________*/
function greqo_blogger_fetch_feed($num_entries=15, $start=1, $type='full')  
{
// *** DATA

	// Hard Parameters
	$request_method = 'GET';

	// Internal
	$_BLOG = array();
	$_api_url = '';
	$_request_url = '';

	// Return
	$FEED_ARRAY = array();


// *** MANIPULATE

	// get blogger user data
	if ( !$_BLOG = greqo_blogger_get_user_data() )
	{
		trigger_error('unable to get blogger user data', E_USER_WARNING);
		return 0;
	}

	// get api url
	if ( !$_api_url = greqo_blogger_get_api_url() )
	{
		trigger_error('unable to get api url', E_USER_WARNING);
		return 0;
	}
		
	// set request url
	$_request_url = "{$_api_url}/feeds/{$_BLOG['blog_id']}/posts/{$type}?start-index={$start}&max-results={$num_entries}";
	
	// set request headers
	#none
	
	// Send request
	if ( !$_RESPONSE = greqo_blogger_request_factory($_request_url, $request_method) )
	{
		trigger_error('request failed -- see error message', E_USER_WARNING);
		return 0;
	}
	
	// Process response
	if ( $_RESPONSE['code_class'] == 2 )
  {
		$xml_feed = $_RESPONSE['body'];
  }
  else
  {
		$_body = htmlspecialchars($_RESPONSE['body']);
		trigger_error("unexpected response (code {$_RESPONSE['code']}) : $_body", E_USER_WARNING);
		return 0;
  }
	
	// exit check
	if ( !empty($xml_feed) ) 
	{
		$FEED_ARRAY = greqo_atom_to_array($xml_feed);
	}
	else
	{
		trigger_error('empty result', E_USER_WARNING);
	}
	

// *** RETURN

	return $FEED_ARRAY;

} // end Fx
/*____________________________________________________________________________*/



// greqo_blogger_get_blog_list
/*____________________________________________________________________________*/
function greqo_blogger_get_blog_list() 
{
// *** DATA

	// Hard Parameters
	$request_method = 'GET';

	// Internal
	$_BLOG = array();
	$_api_url = '';
	$_request_url = 'http://www2.blogger.com/feeds/default/blogs';

	// Return
	$LIST = array();


// *** MANIPULATE

	// get blogger user data
	if ( !$_BLOG = greqo_blogger_get_user_data() )
	{
		trigger_error('unable to get blogger user data', E_USER_WARNING);
		return 0;
	}
	
	// get api url
	if ( !$_api_url = greqo_blogger_get_api_url() )
	{
		trigger_error('unable to get api url', E_USER_WARNING);
		return 0;
	}
	
	// set request url
	$_request_url = "{$_api_url}/feeds/default/blogs";

	// set request headers
	#none
	
	// Send request
	if ( !$_RESPONSE = greqo_blogger_request_factory($_request_url, $request_method) )
	{
		trigger_error('request failed -- see error message', E_USER_WARNING);
		return 0;
	}
	
	// Process response
	if ( $_RESPONSE['code_class'] == 2 )
  {
		$xml_feed = $_RESPONSE['body'];
  }
  else
  {
		$_body = htmlspecialchars($_RESPONSE['body']);
		trigger_error("unexpected response (code {$_RESPONSE['code']}) : $_body", E_USER_WARNING);
		return 0;
  }
	
	// exit check
	if ( !empty($xml_feed) ) 
	{
		$LIST = greqo_atom_to_array($xml_feed);
	}
	else
	{
		trigger_error('empty result', E_USER_WARNING);
	}
	

// *** RETURN

	return $LIST;

} // end Fx
/*____________________________________________________________________________*/



// greqo_blogger_post_entry
/*____________________________________________________________________________*/
function greqo_blogger_post_entry($body, $title='', $blog_id='default') 
{
// *** DATA

	// hard parameter
	$text_type = 'html';
	$request_method = 'POST';
	
	// Internal
	$_BLOG = array();
	$_HEADER = array();
	$_api_url = '';
	$_request_url = '';
	$_atom_data = '';

	// Return
	$ENTRY_DATA = array();


// *** MANIPULATE

	// get blogger user data
	if ( !$_BLOG = greqo_blogger_get_user_data() )
	{
		trigger_error('unable to get blogger user data', E_USER_WARNING);
		return 0;
	}

	// get api url
	if ( !$_api_url = greqo_blogger_get_api_url(1) )
	{
		trigger_error('unable to get api url', E_USER_WARNING);
		return 0;
	}
	
	// set default blog id from user data file if no id passed
	if ( $blog_id == 'default' ) $blog_id = $_BLOG['blog_id'];
	
	// set request url
	$_request_url = "{$_api_url}/feeds/{$blog_id}/posts/full";
	
	// set request headers
	$_HEADER = array( 'Content-type' => 'application/atom+xml' );
	
	// escape html entities in title and content
	$title = greqo_escape_entities($title);
	$body = greqo_escape_entities($body);
	
	// create atom xml
	$_atom_data = <<<XML
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="{$text_type}">$title</title>
  <content type="{$text_type}">$body</content>
</entry>
XML;
	
	// Send request
	if ( !$_RESPONSE = greqo_blogger_request_factory($_request_url, $request_method, $_HEADER, $_atom_data) )
	{
		trigger_error('request failed -- see error message', E_USER_WARNING);
		return 0;
	}
	
	// Process response
	if ( $_RESPONSE['code_class'] == 2 )
  {
		if ( !$ENTRY_DATA = greqo_blogger_parse_post_response($_RESPONSE['body']) ) $ENTRY_DATA = 0;
  }
  else
  {
		$_body = htmlspecialchars($_RESPONSE['body']);
		trigger_error("unexpected response (code {$_RESPONSE['code']}) : $_body", E_USER_WARNING);
		return 0;
  }

	
// *** RETURN

	return $ENTRY_DATA;

} // end Fx
/*____________________________________________________________________________*/




// greqo_blogger_edit_entry
/*____________________________________________________________________________*/
function greqo_blogger_edit_entry($entry_id, $body, $title='') 
{
// *** DATA

	// Hard parameters
	$request_method = 'PUT';
	$text_type = 'html';

	// Internal
	$_BLOG = array();
	$_HEADER = array();
	$_api_url = '';
	$_request_url = '';
	$_atom_data = '';

	// Return
	$ENTRY_DATA = array();


// *** MANIPULATE

	// get blogger user data
	if ( !$_BLOG = greqo_blogger_get_user_data() )
	{
		trigger_error('unable to get blogger user data', E_USER_WARNING);
		return 0;
	}

	// get api url
	if ( !$_api_url = greqo_blogger_get_api_url() )
	{
		trigger_error('unable to get api url', E_USER_WARNING);
		return 0;
	}
	
	// set request url
	$_request_url = "{$_api_url}/feeds/{$_BLOG['blog_id']}/posts/full/$entry_id";
	
	// set request headers
	$_HEADER = array( 'Content-type' => 'application/atom+xml' );
	
	// escape html entities in title and content
	$title = greqo_escape_entities($title);
	$body = greqo_escape_entities($body);
	
	// create atom xml
	$_atom_data = <<<XML
<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="{$text_type}">$title</title>
  <content type="{$text_type}">$body</content>
</entry>
XML;
	
	// Send request
	if ( !$_RESPONSE = greqo_blogger_request_factory($_request_url, $request_method, $_HEADER, $_atom_data) )
	{
		trigger_error('request failed -- see error message', E_USER_WARNING);
		return 0;
	}
	
	// Process response
	if ( $_RESPONSE['code_class'] == 2 )
  {
		if ( !$ENTRY_DATA = greqo_blogger_parse_post_response($_RESPONSE['body']) ) $ENTRY_DATA = 0;
  }
  else
  {
		$_body = htmlspecialchars($_RESPONSE['body']);
		trigger_error("unexpected response (code {$_RESPONSE['code']}) : $_body", E_USER_WARNING);
		return 0;
  }

	
// *** RETURN

	return $ENTRY_DATA;

} // end Fx
/*____________________________________________________________________________*/



// greqo_blogger_delete_entry
/*____________________________________________________________________________*/
function greqo_blogger_delete_entry($entry_id)
{
// *** DATA

	// Hard parameters
	$request_method = 'DELETE';

	// Internal
	$_BLOG = array();
	$_HEADER = array();
	$_api_url = '';
	$_request_url = '';
	$_atom_data = '';

	// Return
	$is_deleted = 0;

	
// *** MANIPULATE

	// get blogger user data
	if ( !$_BLOG = greqo_blogger_get_user_data() )
	{
		trigger_error('unable to get blogger user data', E_USER_WARNING);
		return 0;
	}

	// get api url
	if ( !$_api_url = greqo_blogger_get_api_url(1) )
	{
		trigger_error('unable to get api url', E_USER_WARNING);
		return 0;
	}
		
	// set request url
	$_request_url = "{$_api_url}/feeds/{$_BLOG['blog_id']}/posts/full/$entry_id";
	
	// set request headers
	$_HEADER = 0;
	
	// Send request
	if ( !$_RESPONSE = greqo_blogger_request_factory($_request_url, $request_method, $_HEADER) )
	{
		trigger_error('request failed -- see error message', E_USER_WARNING);
		return 0;
	}
	
	// Process response
	if ( $_RESPONSE['code_class'] == 2 || $_RESPONSE['code_class'] == 1 )
  {
		$is_deleted = 1;
  }
  else
  {
		$_body = htmlspecialchars($_RESPONSE['body']);
		trigger_error("unexpected response (code {$_RESPONSE['code']}) : $_body", E_USER_WARNING);
		return 0;
  }


// *** RETURN

	return $is_deleted;

} // end Fx
/*____________________________________________________________________________*/


?>
